%{
# include "parser.h"
static ChainingHashMap *result;
extern FILE *ucesin;
%}

%union {
	char *string;
	float virgula;
	int digits;
	char *number;
	ChainingHashMap *map;
	UCE *uce;
}

%token <string> STRING
%token <digits> DIGITS
%token <virgula> FLOAT
%token <number> NUMBER

%token LABEL_UCE LABEL_NAME LABEL_MAXSTUDENTS 
%token OPEN CLOSE EQUAL STOP

%start Document

%type <map> Uces
%type <uce> Uce UceDataList
%type <digits> UceMaxStudents
%%

Document	: Uces { ; }
		| { ; }
		;

Uces	 	: Uces Uce { insertUce($2); }
	 	| Uce { insertUce($1); }
	 	;

Uce		: STRING OPEN UceDataList CLOSE { $$ = insertName($1,$3); }
		;

UceDataList	: UceDataList UceMaxStudents { $$ = insertMax($1,$2); }
		| { $$ = NULL; }
		;

UceMaxStudents	: LABEL_MAXSTUDENTS EQUAL DIGITS STOP { $$ = $3; }
		;

%%

static int uceEqual (void *a, void *b) {
	UCE *x = (UCE *) a;
	UCE *y = (UCE *) b;
	if (!strcmp(x->name,y->name)) return 1;
	else return 0;
}

static void insertUce (UCE *uce) {
	if (!putChaining(result,uce->name,uce)) {
		logMessage("io.files.uces","parser.y","insertUce","Elemento não foi inserido na hash",ERROR);
	}
}
static UCE * insertName(char *name, UCE *uce) {
	if (!uce) uce = newUCE();
	uce->name = name;
	return uce;
}
static UCE * insertMax(UCE *uce, int max) {
	if (!uce) uce = newUCE();
	uce->maxStudents = max;
	return uce;
}

/*int yywrap () {
	return 1;
}*/

int yyerror (char *err) {
	printf("%s\n",err);
	return 1;
}
int equalityString (void *a, void *b) {
	return !strcmp(a,b);
}
ChainingHashMap * readUCEs (FILE *fp) {
	ucesin = fp;
	result = newChainingHashMap(UCE_HASHMAP_SIZE);
	result->hash = portugueseHash;
	result->eq = equalityString;
	if (yyparse()) {
		printf("ERRO\n");
		return NULL;
	}
	return result; 
}

void writeUCEs (ChainingHashMap *map, FILE *fp) {
	LinkedList *keyList = keySetChaining(map);
	UCE *tmp;
	for (;keyList;keyList=keyList->next) {
		tmp = getChaining(map,getData(keyList));
		fprintf(fp,"'%s' {\n",tmp->name);
		if (tmp->maxStudents != 0 )
			fprintf(fp,"\tmaxAlunos=%d;\n",tmp->maxStudents);
		fprintf(fp,"}\n");
	}
}
